package seven;

import java.util.Iterator;
import java.util.Set;

import javax.management.Attribute;
import javax.management.MBeanInfo;
import javax.management.MBeanServerConnection;
import javax.management.MBeanServerInvocationHandler;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

/**
 * 前面用Html、jconsole等方法连接上了MBeanServer，并能够通过这些界面来操纵MBean。
 * 但有时我们需要不借助这些客户端，而是在自己的程序来操纵这些MBean，这就要求我们知道如何在代码里连接MBean。
 */
@SuppressWarnings("rawtypes")
public class Client {
	
	public static void main(String[] args) throws Exception {
		
		JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/server");
		JMXConnector jmxc = JMXConnectorFactory.connect(url,null);
		MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
		ObjectName mbeanName = new ObjectName("liuys:name=helloWorld");
		//把所有的Domain都打印出来
		System.out.println("Domains:-----------------------");
		String[] domains = mbsc.getDomains();
		for (int i = 0; i < domains.length; i++) {
			System.out.println("Domain"+i+"="+domains[i]);
		}
		//MBean的总数
		System.out.println("MBean count="+mbsc.getMBeanCount());
		//对name属性的操作。  属性名第一个字母要大写
		mbsc.setAttribute(mbeanName, new Attribute("Name", "ZHANGSAN"));//设值
		System.out.println("Name="+mbsc.getAttribute(mbeanName, "Name"));//取值
		//得到proxy代理后直接调用的方式
		HelloMXBean proxy = (HelloMXBean)MBeanServerInvocationHandler.newProxyInstance(mbsc, mbeanName, HelloMXBean.class, false);
		proxy.sayHello();
		proxy.sayHello("liubei");
		//远程调用的方式
		mbsc.invoke(mbeanName, "sayHello", null, null);
		mbsc.invoke(mbeanName, "sayHello", new Object[]{"guanyu"}, new String[]{String.class.getName()});
		//得到mbean的信息
		MBeanInfo info = mbsc.getMBeanInfo(mbeanName);
		System.out.println("Hello class:"+info.getClassName());
		System.out.println("Hello attribute:"+info.getAttributes()[0].getName());
		System.out.println("Hello operation:"+info.getOperations()[0].getName());
		//得到所有的mbean的ObjectName
		System.out.println("All ObjectName:--------------------------");
		Set set = mbsc.queryMBeans(null, null);//参数为空表示查询所有MBean
		for(Iterator it = set.iterator(); it.hasNext();){
			ObjectInstance oi = (ObjectInstance)it.next();
			System.out.println(oi.getObjectName());
		}
		//注销
		mbsc.unregisterMBean(mbeanName);
		//关闭mbeanServer连接
		jmxc.close();
	}
	
}
